package com.guet.careapp.controller.rest.controller.contacts;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guet.careapp.common.Constants;
import com.guet.careapp.controller.rest.common.errorCode.Error;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCode;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCodeFactory;
import com.guet.careapp.pojo.TUserGuardianInfo;
import com.guet.careapp.pojo.TUserInfo;
import com.guet.careapp.pojo.TUserRelation;
import com.guet.careapp.pojo.TUserUnderGuardiansInfo;
import com.guet.careapp.pojo.rest.AjaxReturn;
import com.guet.careapp.service.IUserGuardianInfoService;
import com.guet.careapp.service.IUserInfoService;
import com.guet.careapp.service.IUserRelationService;
import com.guet.careapp.service.IUserUnderGuardiansInfoService;
import com.guet.careapp.utils.ConvertUtils;
import com.guet.careapp.utils.TimeHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * Created by LXM on 2017/10/14.
 *
 * @author LXM
 * @version 1.0
 * @description
 * @datetime 20:17
 */
@Path("/contacts")
public class ContactsController {

    Logger logger = LoggerFactory.getLogger(ContactsController.class);

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserRelationService userRelationService;

    @Autowired
    private IUserGuardianInfoService guardianInfoService;

    @Autowired
    private IUserUnderGuardiansInfoService underGuardiansInfoService;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 建立监护与被监护关系.
     * <p>
     * gid  监护人的ID
     * bgid 被监护人的ID
     * grant 授权
     *
     * @return ErrorCode 返回码
     */
    @POST
    @Path("/build")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String buildRelationship(String resource) {

        AjaxReturn ajaxReturn = null;

        TUserGuardianInfo guardian;
        TUserUnderGuardiansInfo userUnderGuardian;
        Map map = ConvertUtils.jsonToMap(resource);
        Integer g;
        Integer u;
        TUserInfo tempUser_u;
        TUserInfo tempUser_g;
        //判断参数是否正确
        try {
            if (map.size() != 3 || map.get("gid") == null || map.get("bgid") == null)
                return gson.toJson(new AjaxReturn(Constants.INVAILD_CODE, Constants.INVAILD));

        } catch (Exception e) {
            logger.error("参数无效");
            return gson.toJson(new AjaxReturn(Constants.INVAILD_CODE, Constants.INVAILD));
        }
        // 查找是否存在这两个用户
        try {
            g = Integer.parseInt(map.get("gid") + "");
            u = Integer.parseInt(map.get("bgid") + "");

            //查询这两个id的用户是否存在
            tempUser_u = userInfoService.findById(u);
            tempUser_g = userInfoService.findById(g);

            if (tempUser_u == null) {
                ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
                return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), "被监护人不存在,id" + u + "  不是任何用户的id，请核查"));
            }
            if (tempUser_g == null) {
                ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
                return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), "监护人不存在,id" + u + "  不是任何用户的id，请核查"));
            }

            guardian = guardianInfoService.findById(g);
            userUnderGuardian = underGuardiansInfoService.findById(u);


            //当监护人不存在当时候，他又想添加别人，那他就是监护人了
            if (guardian == null) {
                guardian = new TUserGuardianInfo();
                guardian.setTUserInfo(tempUser_g);
                guardian.setUId(tempUser_g.getUId());
                guardianInfoService.saveOrUpdate(guardian);

            }
            //当被监护人不存在的时候
            if (userUnderGuardian == null) {

                //如果是未分类的用户。又被添加，那么就当它是被监护人了，添加到被监护人
                userUnderGuardian = new TUserUnderGuardiansInfo();
                userUnderGuardian.setTUserInfo(tempUser_u);
                userUnderGuardian.setAge(0);
                userUnderGuardian.setUId(tempUser_u.getUId());
                underGuardiansInfoService.saveOrUpdate(userUnderGuardian);

//                // 填充参数，建立关系
//                TUserRelation relation = new TUserRelation();
//                relation = new TUserRelation();
//                relation.setUgInfoId(newUnderGuardians);
//                relation.setGInfoId(guardian);
//                relation.setGranted(1);
//                relation.setEstablishTime(TimeHelper.getTime());
//                try {
//                    userRelationService.save(relation);
//                    ErrorCode errorCode = ErrorCodeFactory.get(Error.Success);
//                    return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    ErrorCode errorCode = ErrorCodeFactory.get(Error.Unkonwn);
//                    return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorCode errorCode = ErrorCodeFactory.get(Error.TypeError);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
        }


        //查询这个关系是否存在
        TUserRelation relation;
        Map<String, Object> fieldMap = new HashMap();
        fieldMap.put("g_info_id", g);
        fieldMap.put("ug_info_id", u);
        relation = userRelationService.findByField(fieldMap);
        if (null != relation) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.AreadyExist);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
        }

        // 填充参数，建立关系
        relation = new TUserRelation();
        relation.setUgInfoId(userUnderGuardian);
        relation.setGInfoId(guardian);
        relation.setGranted(1);
        relation.setEstablishTime(TimeHelper.getTime());
        try {
            userRelationService.save(relation);
            ErrorCode errorCode;
            //更新被监护人的type值
            tempUser_u.setType("2");
            userInfoService.update(tempUser_u);
            errorCode = ErrorCodeFactory.get(Error.Success);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));

        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.Unkonwn);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
        }

    }

    /**
     * 解除监护人与被监护人的绑定关系.
     *
     * @return 返回码
     * @ gid 监护人id
     * @ beid 被监护人id
     */
    @DELETE
    @Path("/unbinding")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String unbinding(String resource) {
        TUserGuardianInfo guardian;
        TUserUnderGuardiansInfo userUnderGuardian;
        TUserRelation relation;
        Integer g;
        Integer u;
        Map map = ConvertUtils.jsonToMap(resource);
        //判断参数是否正确
        try {
            if (map.size() != 2 || map.get("gid") == null || map.get("bgid") == null)
                return gson.toJson(new AjaxReturn(Constants.INVAILD_CODE, Constants.INVAILD));

        } catch (Exception e) {
            logger.error("参数无效");
            return gson.toJson(new AjaxReturn(Constants.INVAILD_CODE, Constants.INVAILD));
        }
        // 解析Json字符串
        try {
            g = Integer.parseInt(map.get("gid") + "");
            u = Integer.parseInt(map.get("bgid") + "");
            guardian = guardianInfoService.findById(g);
            userUnderGuardian = underGuardiansInfoService.findById(u);

            if (guardian == null || userUnderGuardian == null) {
                ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
                return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
            }
        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.TypeError);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
        }
        try {
            Map<String, Object> fieldMap = new HashMap();
            fieldMap.put("g_info_id", g);
            fieldMap.put("ug_info_id", u);
            relation = userRelationService.findByField(fieldMap);
            if (null == relation) {
                ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
                return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
            }
            userRelationService.deleteById(relation.getId());
        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.Unkonwn);
            return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
        }

        ErrorCode errorCode = ErrorCodeFactory.get(Error.Success);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));

    }

    /**
     * 查询被监护人所属的监护人，这是一个一对多的关系.
     *
     * @return 一个json数组的字符串，包含的信息是监护人的ID和昵称
     * @ beid 被监护人的ID
     */
    @POST
    @Path("/g")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String searchRelationship(String json) {
        //用于存放用户的数据
        Integer u;
        Map<String, Object> fieldMap;
        Gson gson;
        List<Map> gList;

        Map map = ConvertUtils.jsonToMap(json);
        // 解析Json字符串
        try {
            u = Integer.parseInt(map.get("bgid") + "");
        } catch (Exception e) {

            return gsonStr(Error.TypeError);
        }

        fieldMap = new HashMap<>();
        fieldMap.put("ug_info_id", u);
        List<TUserRelation> list = userRelationService.findAllByField(fieldMap);
        //当此用户不存在的时候
        if (list.size() == 0) {
            return gsonStr(Error.NotFond);

        }
        gList = new ArrayList<>();

        //选择部分信息返回
        for (TUserRelation r : list) {
            fieldMap = new HashMap<>();
            fieldMap.put("u_id", r.getGInfoId().getTUserInfo().getUId());
            fieldMap.put("username", r.getGInfoId().getTUserInfo().getName());
            fieldMap.put("telphone", r.getGInfoId().getTUserInfo().getTelphone());
            fieldMap.put("image", r.getGInfoId().getTUserInfo().getImage());
            fieldMap.put("type",  r.getGInfoId().getTUserInfo().getType());
            fieldMap.put("register_time",  r.getGInfoId().getTUserInfo().getRegisTime());
            fieldMap.put("device_id",  r.getGInfoId().getTUserInfo().getDeviceId());
            gList.add(fieldMap);

        }
        gson = new Gson();
        try {
            return gsonObj(Error.Success, gList);

        } catch (Exception e) {
            return gsonStr(Error.Unkonwn);

        }
    }


    /**
     * 查询监护人所属的被监护人，这是一个一对多的关系.
     *
     * @return 一个json数组的字符串，包含的信息是
     * @ gid 被监护人的ID
     */
    @POST
    @Path("/ug")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String searchRelation(String json) {
        //用于存放用户的数据
        JSONObject jsonObject;
        Integer g;
        Map<String, Object> fieldMap;
        List<Map> gList;

        Map map = ConvertUtils.jsonToMap(json);
        // 解析Json字符串
        try {
            g = Integer.parseInt(map.get("gid") + "");
        } catch (Exception e) {

            return gsonStr(Error.TypeError);
        }

        fieldMap = new HashMap<>();
        fieldMap.put("g_info_id", g);
        List<TUserRelation> list = userRelationService.findAllByField(fieldMap);
        //当此用户不存在的时候
        if (list.size() == 0) {
            return gsonStr(Error.NotFond);

        }
        gList = new ArrayList<>();

        //选择部分信息返回
        for (TUserRelation r : list) {
            fieldMap = new HashMap<>();
            fieldMap.put("u_id", r.getUgInfoId().getTUserInfo().getUId());
            fieldMap.put("username",r.getUgInfoId().getTUserInfo().getName());
            fieldMap.put("telphone", r.getUgInfoId().getTUserInfo().getTelphone());
            fieldMap.put("image", r.getUgInfoId().getTUserInfo().getImage());
            fieldMap.put("type",  r.getUgInfoId().getTUserInfo().getType());
            fieldMap.put("register_time",  r.getUgInfoId().getTUserInfo().getRegisTime());
            fieldMap.put("device_id",  r.getUgInfoId().getTUserInfo().getDeviceId());
            gList.add(fieldMap);

        }
        gson = new Gson();
        try {
            return gsonObj(Error.Success, gList);
        } catch (Exception e) {
            return gsonStr(Error.Unkonwn);
        }
    }

    /**
     * 转让监护人与被监护人的绑定关系.
     *
     * @return 返回码
     * @ gid 监护人id
     * @ beid 被监护人id
     * @ otherid 第三个监护人的id
     */
    @POST
    @Path("/assignment")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String assignment(String json) {

        Integer g, ug, o;
        TUserGuardianInfo guardian;
        TUserUnderGuardiansInfo userUnderGuardian;
        TUserGuardianInfo other;
        Map map = ConvertUtils.jsonToMap(json);
        // 解析Json字符串
        try {
            g = Integer.parseInt(map.get("gid") + "");
            ug = Integer.parseInt(map.get("bgid") + "");
            o = Integer.parseInt(map.get("otherid") + "");
        } catch (Exception e) {
            return gsonStr(Error.TypeError);
        }
        try {
            guardian = guardianInfoService.findById(g);
            userUnderGuardian = underGuardiansInfoService.findById(ug);
            other = guardianInfoService.findById(o);
            if (null == guardian || null == userUnderGuardian || null == other)
                return gsonStr(Error.NotFond);
        } catch (Exception e) {
            return gsonStr(Error.NotFond);
        }
        Error result = userRelationService.assignment(g, ug, o);

        return gsonStr(result);

    }


    private String gsonStr(Error error) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
    }

    private String gsonObj(Error error, Object object) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning(), object));
    }
}
